import Request from './request'
import apiList from './api.ts'
const urlRequest = new Request();
import config from "@/common/config"
const baseUrl = config.baseUrl
export default async function http(
	url : string,
	data = {},
	toastBefore = '', // 请求前加载提示
	toastAfter = true, // 请求后错误提示
) {
	let api = getApiPath(url);
	/* 请求之前拦截器 */
	urlRequest.interceptor.request((config, cancel) => {
		let token = uni.getStorageSync('token');
		// let token = '674d0b0e-08b7-4420-ab21-8e0e57ab0119';
		if (!token) {
			console.log(`暂未登录,已阻止此次API请求: '${api.url}'`)
		}
		token && urlRequest.setConfig((config) => {
			config.header.token = token
		})
		if (toastBefore !== '') {
			uni.showLoading({
				title: toastBefore,
				mask: true
			});
		}
		return config
	});
	/* 请求之后拦截器 */
	urlRequest.interceptor.response((response) => {
		uni.hideLoading();
		console.log(response);
		if ( response.code != '1') {
			if (response.msg == '请登录后操作' || response.msg == '账号不存在') {
				uni.removeStorageSync('token')
				uni.showToast({
					title: response.msg || '未登录过期或者过期',
					icon: 'none',
					duration: 1000,
					mask: true
				});
				setTimeout(() => {
					uni.navigateTo({
						url: '/pages/login/index'
					})
					
				}, 800)
			} else if (toastAfter) {
				uni.showToast({
					title: response.msg || '请求出错,稍后重试',
					icon: 'none',
					duration: 1000,
					mask: true
				});
			}
		}

		// token过期注销
		if (response.code === 'login' || response.code === 'expire') {
			uni.removeStorageSync('token')
			uni.showToast({
				title: response.msg || '未登录过期或者过期',
				icon: 'none',
				duration: 1000,
				mask: true
			});
			setTimeout(() => {
				uni.navigateTo({
					url: '/pages/login/index'
				})
			}, 800)
		}
		return response
	})

	return urlRequest.request({
		url: baseUrl + api.url,
		data,
		method: api.method
	})

}

// 组装接口路径
function getApiPath(url : string) {
	let apiArray = url.split(".");
	let api = apiList;
	apiArray.forEach(v => {
		api = api[v];
	});
	return api;
}